package apis

import (
	"crypto/md5"
	"fmt"
	"github.com/gin-gonic/gin"
	"main/common"
	"main/models"
	"main/vto"
	"strconv"
)



// 获取用户列表
func GetUserList(c *gin.Context) {
	var user []models.User
	var page, limit int
	page, err := strconv.Atoi(c.DefaultQuery("page", "0"))
	if err != nil {
		common.ReturnError(c, fmt.Sprintf("%v", err) ,10001)
		return
	}
	limit, err = strconv.Atoi(c.DefaultQuery("limit", "0"))
	if err != nil {
		common.ReturnError(c, fmt.Sprintf("%v", err) ,10001)
		return
	}
	models.DB = models.DB.Order("id desc")
	res, page, limit := common.Paginate(&user, page, limit)
	common.ReturnPageDate(c, res, page, limit)
}

// 获取用户详情
func GetUser(c *gin.Context) {
	var user models.User
	models.DB.Find(&user, c.Param("id"))
	if user.CreatedAt == 0 {
		common.ReturnError(c,"暂无数据",400)
	}else{
		common.ReturnSuccess(c,user,"OK",200)
	}
}

// 添加用户
func AddUser(c *gin.Context) {
	var user models.User
	var form vto.UserCreateForm

	c.Bind(&form)

	if _,err := common.Validator(&form, true); err != nil {
		common.ReturnError(c, fmt.Sprintf("%v", err) ,10001)
	}else {
		password := fmt.Sprintf("%x", md5.Sum([]byte(form.Password)))
		user = models.User{
			Email:    form.Email,
			Name:     form.Name,
			Password: password,
			Gender:   form.Gender,
		}
		models.DB.Create(&user)
		common.ReturnSuccess(c,user,"OK",200)
	}
}

// 更新用户
func UpdateUser(c *gin.Context) {
	var user models.User
	var form vto.UserCreateForm

	models.DB.Find(&user, c.Param("id"))
	if user.CreatedAt == 0 {
		common.ReturnError(c,"暂无数据",400)
		return
	}

	form.Password = user.Password
	c.Bind(&form)
	if _,err :=common.Validator(&form,true); err != nil {
		common.ReturnError(c,fmt.Sprintf("%v", err),400)
		return
	}
	user.Name = form.Name
	user.Gender = form.Gender
	user.Email = form.Email
	models.DB.Save(&user)
	common.ReturnSuccess(c,user,"OK",200)

}

// 删除用户
func DelUser(c *gin.Context) {
	var user models.User
	models.DB.Find(&user, c.Param("id"))
	if user.CreatedAt == 0 {
		common.ReturnError(c,"暂无数据",400)
	}else {
		models.DB.Delete(&user)
		common.ReturnSuccess(c,user,"OK",200)
	}
}
